package com.cjk.foundation.util;

import java.io.BufferedReader;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestUtil {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);
	
	public static String getContextUrl(HttpServletRequest request){
		StringBuffer url = request.getRequestURL();  
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString(); 
	}
	
	public static String getDomain(HttpServletRequest request){
		return request.getScheme() + "://" + request.getServerName() + request.getContextPath();
	}
	
	public static String getIp(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public static String getParamsString(HttpServletRequest request){
		String params = null;
		try {
			BufferedReader reader = request.getReader();
	        String line = "";
	        StringBuffer inputString = new StringBuffer();
	        while ((line = reader.readLine()) != null) {
	            inputString.append(line);
	        }
	        params = inputString.toString();
	        request.getReader().close();
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
		return params;
	}
}
